export PATH="/bin:/sbin:/tmp"
export HOME=$(awk -F: "/^${USER:-root}:/{print \$6}" /etc/passwd)
export HOME=${HOME:-/root}
export TZ=$(cat /etc/TZ)
export EDITOR="vi"
[ -f /etc/sensor/model ] && export SENSOR=$(cat /etc/sensor/model)

network_hostname=$(hostname -s)
ifaces=$(ifconfig | awk '/^[^( |lo)]/{print $1}')

if4=$(ip -4 r | awk '/default/{print $5; exit}')
[ -z "$if4" ] && if4=$(ip -4 r | awk '{print $3; exit}')

if6=$(ip -6 r | sed -nE '/default/s/.+dev (\w+).+?/\1/p' | head -n 1)
[ -z "$if6" ] && if6=$(ip -6 r | awk '!/local/{print $3; exit}')

[ -n "$if4" ] && {
	grep -q 'inet\|dhcp' /etc/network/interfaces.d/$if4 && dhcp="true"
	gw4=$(ip -4 r | sed -nE "/default/s/.+ via ([0-9\.]+).+?/\1/p")
	ip4=$(ip -4 a show dev "$if4" | sed -nE '/inet/s/.+inet ([0-9\.]+).+/\1/p' | uniq)
}

[ -n "$if6" ] && {
	gw6=$(ip -6 r | sed -nE "/default/s/.+ via ([a-f0-9:]+).+?/\1/p")
	ip6=$(ip -6 a show dev "$if6" | awk '/inet6 /{
		split($2, a, "/"); ip = a[1]; p = a[2];
		prio = (ip !~ /^f/) ? 0 : 2; prio += (p == 128) ? 0 : 1;
		if (!seen[prio]++) res[prio] = ip
	} END {
		for (i = 0; i < 4; i++) if (res[i]) { print res[i]; exit }
	}')
}

[ -n "${if4:-$if6}" ] && mac=$(cat /sys/class/net/${if4:-$if6}/address)

ip_address=""

alias tb="send2termbin"
alias ver=". /etc/profile"

R65OR="\e[38;5;130m%65s\e[0m\n"
R65GD="\e[38;5;244m%65s\e[0m\n"
R65GL="\e[38;5;251m%65s\e[0m\n"

if [ "$PS1" ]; then
	[ -f /etc/os-release ] && . /etc/os-release
	[ -f /etc/banner ] && echo -e "$(cat /etc/banner)"
	printf $R65GD "$IMAGE_ID"
	printf $R65GD "$BUILD_ID"
	echo
	[ -n "$mac" ] && printf $R65GL "$mac as ${if4:-$if6}"
	[ -n "$ip6" ] && printf $R65GL "$ip6 (IPv6)"
	[ -n "$ip4" ] && printf $R65GL "$ip4 (IPv4)"
	[ -z "$ip4$ip6" ] && printf $R65GL "No IP address"
	echo
	printf $R65OR "$(uptime)"
	echo

	if [ "$(id -u)" -eq 0 ]; then
		export PS1="\[\e[38;5;208m\]\u\[\e[m\]@\[\e[38;5;153m\]\h\[\e[m\]\[\e[38;5;214m\] \W\[\e[m\]\\# "
	else
		export PS1='\u@\h:\w\$ '
	fi
fi

for i in /etc/profile.d/*; do
	[ -r "$i" ] && . $i
done; unset i

resize > /dev/null
